﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

using kxcxw.Data;
using System.Collections;
using kxcxw.Data.Entities;
using System.Web.Security;
using System.IO;
using kxcxw.Business;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using kxcxw.Data.Common;
using System.Text.RegularExpressions;
using Webdiyer.WebControls.Mvc;
using System.Data.Entity.Validation;
using KXCXW.Web.CommonClass;
using KXCXW.Web.Models;

namespace KXCXW.Web.Controllers
{
    public partial class HomeController : Controller
    {
        /// <summary>
        /// 图片路径字典表
        /// </summary>
        static Dictionary<string, string> PicNameDictionary = new Dictionary<string, string>();
        private KXCXWDBContext db = new KXCXWDBContext();
        private CommonRepositories comm = new CommonRepositories();
        private ImgHelper conlist = null;

        private void initImgPoth()
        {
            string rootpath = Server.MapPath("~/Content/xml/imgconfig.xml");
            conlist = new ImgHelper(rootpath);
        }
        public ActionResult Index()
        {
            ViewBag.Message = "";

            ViewData["dlCount"] = "0";
            ViewData["BoutuqueArea"] = comm.getAreaProductList(DataConstants.WebShop, DataConstants.JinPingItemID);//精品区
            ViewData["Characteristic"] = comm.getAreaProductList(DataConstants.WebShop, DataConstants.TeSheItemID);//特色区
            ViewData["type"] = 1;
            ViewData["time"] = DateTime.Now.ToString();
            #region 公告
            IList<SysItemDetial> AnnouncementInfoType = comm.getTypeListById(DataConstants.AnnouncementTypeItemID);
            ViewBag.AnnouncementTypes = AnnouncementInfoType;
            if (AnnouncementInfoType != null && AnnouncementInfoType.Count > 0)
            {
                foreach (SysItemDetial item in AnnouncementInfoType)
                {
                    //取前8个
                    ViewData[item.ItemDeitalID] = db.AnnouncementInfoes.Where(p => p.ItemID.Equals(item.ItemDeitalID))
                        .OrderByDescending(p => p.CreateDate).Take(8)
                        .ToList<AnnouncementInfo>();
                }
            }
            #endregion
            #region 促销类别
            IList<SysItemDetial> lstSysItemDetail = comm.getTypeListById(DataConstants.PromotionTypeItemID);
            ViewBag.PromotionTypes = lstSysItemDetail;
            #endregion
            #region 商品列表信息
            DateTime TempDate = DateTime.Now.AddDays(-DataConstants.ExpirationDay);
            if (lstSysItemDetail != null && lstSysItemDetail.Count > 0)
            {
                var infolist = db.PublichInformations.Where(q => (q.EndDate == null && q.PublishDate >= TempDate) || q.EndDate >= DateTime.Now).Where(q => q.Status == DataConstants.Normal).Where(p => p.InfoType == 1);
                foreach (SysItemDetial item in lstSysItemDetail)
                {
                    //取前8个
                    ViewData[item.ItemDeitalID] = infolist.Where(p => p.PromotionType.Equals(item.ItemDeitalID)).OrderByDescending(p => p.PriorityLevel)
                        .ThenByDescending(p => p.TopDate)
                        .ThenByDescending(p => p.AlertDate)
                        .ThenByDescending(s => s.PublishDate).Take(16)
                        .ToList<PublichInformation>();
                }
            }
            #endregion
            #region 活动信息列表
            ViewData["ActivityList"] = (from q in db.Activitys
                                        where q.ShopType == 1
                                        && ((q.EndDate == null && q.CreateDate >= TempDate) || q.EndDate >= DateTime.Now)
                                        && q.Status == DataConstants.Normal
                                        orderby q.CreateDate descending
                                        select q).Take(10).ToList<Activity>();
            #endregion
            #region 火热排行
            ViewData["HotPop"] = (from q in db.PublichInformations
                                  where q.InfoType == 1
                                  && ((q.EndDate == null && q.PublishDate >= TempDate) || q.EndDate >= DateTime.Now)
                                  orderby q.VisitsNumber descending
                                  select q).Take(5).ToList<PublichInformation>();
            #endregion
            #region 导购排行
            List<Daogou> daogoulist = comm.getDaoGouPopList(DataConstants.WebShop);
            ViewData["DaoGouPop"] = daogoulist;
            #endregion
            return View();
        }
        public ActionResult EntityStore()
        {
            ViewData["dlCount"] = "0";
            ViewData["BoutuqueArea"] = comm.getAreaProductList(DataConstants.EntityShop, DataConstants.JinPingItemID);//精品区
            ViewData["Characteristic"] = comm.getAreaProductList(DataConstants.EntityShop, DataConstants.TeSheItemID);//特色区
            ViewData["type"] = 2;

            #region 公告
            IList<SysItemDetial> AnnouncementInfoType = comm.getTypeListById(DataConstants.AnnouncementTypeItemID);
            ViewBag.AnnouncementTypes = AnnouncementInfoType;
            if (AnnouncementInfoType != null && AnnouncementInfoType.Count > 0)
            {
                foreach (SysItemDetial item in AnnouncementInfoType)
                {
                    //取前8个
                    ViewData[item.ItemDeitalID] = db.AnnouncementInfoes.Where(p => p.ItemID.Equals(item.ItemDeitalID))
                        .OrderByDescending(p => p.CreateDate).Take(8)
                        .ToList<AnnouncementInfo>();
                }
            }
            #endregion
            #region 促销类别
            IList<SysItemDetial> lstSysItemDetail = comm.getTypeListById(DataConstants.PromotionTypeItemID);
            ViewBag.PromotionTypes = lstSysItemDetail;
            #endregion
            #region 商品列表信息
            DateTime TempDate = DateTime.Now.AddDays(-DataConstants.ExpirationDay);
            if (lstSysItemDetail != null && lstSysItemDetail.Count > 0)
            {
                var infolist = db.PublichInformations.Where(q => (q.EndDate == null && q.PublishDate >= TempDate) || q.EndDate >= DateTime.Now).Where(q => q.Status == DataConstants.Normal).Where(p => p.InfoType == 2);
                foreach (SysItemDetial item in lstSysItemDetail)
                {
                    //取前8个
                    ViewData[item.ItemDeitalID] = infolist.Where(p => p.PromotionType.Equals(item.ItemDeitalID))
                        .OrderByDescending(p => p.PriorityLevel)
                        .OrderByDescending(p => p.TopDate)
                        .OrderByDescending(p => p.AlertDate)
                        .OrderByDescending(p => p.PublishDate).Take(16)
                        .ToList<PublichInformation>();
                }
            }
            #endregion
            #region 活动信息列表
            ViewData["ActivityList"] = (from q in db.Activitys
                                        where q.ShopType == 2
                                        && ((q.EndDate == null && q.CreateDate >= TempDate) || q.EndDate >= DateTime.Now)
                                        && q.Status == DataConstants.Normal
                                        orderby q.CreateDate descending
                                        select q).Take(10).ToList<Activity>();
            #endregion
            #region 火热排行
            ViewData["HotPop"] = (from q in db.PublichInformations
                                  where q.InfoType == 2
                                  && ((q.EndDate == null && q.PublishDate >= TempDate) || q.EndDate >= DateTime.Now)
                                  orderby q.VisitsNumber descending
                                  select q).Take(5).ToList<PublichInformation>();
            #endregion
            #region 导购排行
            List<Daogou> daogoulist = comm.getDaoGouPopList(DataConstants.EntityShop);
            ViewData["DaoGouPop"] = daogoulist;
            #endregion
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
        [Authorize]
        public ActionResult SelectType()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">1:网店  2：实体店</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SelectCategory(string id)
        {
            IEnumerable<SysItemDetial> categoryTree = comm.getTypeListById(DataConstants.ProductTypeItemID);
            ViewData["type"] = id;
            return View(categoryTree);
        }
        [Authorize]
        public ActionResult WebShop(string id)
        {
            var sl = comm.getTypeListByIdForDropDownList(DataConstants.PromotionTypeItemID);
            var s2 = comm.getTypeListByIdForDropDownList(DataConstants.SourceTypeItemID);
            ViewBag.PromotionType = new SelectList(sl, "Id", "Name", "288602C8-094D-445B-B51F-52FCA8A9551C");
            ViewBag.SourceList = new SelectList(s2, "Id", "Name", "FF2BB1F4-E4D7-43D7-9454-B478462993F7");
            ViewData["categoryName"] = comm.getCategroyLine(id);
            PublichInformation pinfo = new PublichInformation();
            pinfo.ItemDeitalID = id;
            pinfo.InfoType = 1;
            pinfo.Other = "输入赠品名称";
            pinfo.ShopUrl = "http://";
            ViewBag.UserKey = Membership.GetUser().ProviderUserKey.ToString();
            ViewData["type"] = 1;
            return View(pinfo);
        }
        [Authorize]
        public ActionResult EntityShop(string id)
        {
            var sl = comm.getTypeListByIdForDropDownList(DataConstants.PromotionTypeItemID);
            ViewBag.PromotionType = new SelectList(sl, "Id", "Name", "288602C8-094D-445B-B51F-52FCA8A9551C");
            ViewData["categoryName"] = comm.getCategroyLine(id);
            PublichInformation pinfo = new PublichInformation();
            pinfo.ItemDeitalID = id;
            pinfo.InfoType = 2;
            pinfo.Other = "输入赠品名称";
            ViewBag.UserKey = Membership.GetUser().ProviderUserKey.ToString();
            ViewData["type"] = 2;
            return View(pinfo);
        }

        public ActionResult ProductList(string categoryId, int? typeId, string sortOrder, int? page = 1)
        {
            var Category = (from q in db.SysItemDetials where q.ItemDeitalID == categoryId select q).FirstOrDefault();
            ViewData["CategoryName"] = Category != null ? Category.itemDetialName : "";
            ViewData["categoryId"] = categoryId;
            ViewData["type"] = typeId != null ? typeId.ToString() : "";
            #region 跟据类别获得商品列表
            IQueryable<PublichInformation> infolist = comm.getProductListByCategory(categoryId);

            if (typeId != null)
            {
                infolist = infolist.Where(q => q.InfoType == typeId);
            }
            ViewData["resultCount"] = infolist.Count();
            #region 筛选信息
            double highestPrice = 0;
            if (infolist != null && infolist.Count() > 0)
                highestPrice = Convert.ToDouble(infolist.Max(s => s.PresentPrice));
            ViewData["highestPrice"] = highestPrice;

            if (Request.QueryString["p"] != null)
            {
                string pvalue = Request.QueryString["p"].ToString();
                if (pvalue != "all")
                {
                    string[] arr = pvalue.Split('-');
                    decimal minPrice = Convert.ToDecimal(arr[0]);
                    infolist = infolist.Where(s => s.PresentPrice > minPrice);
                    if (arr[1] != "")
                    {
                        decimal maxPrice = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.PresentPrice < maxPrice);
                    }
                }
            }
            if (Request.QueryString["d"] != null)
            {
                string dvalue = Request.QueryString["d"].ToString();
                if (dvalue != "all")
                {
                    string[] arr = dvalue.Split('-');
                    decimal minDiscount = Convert.ToDecimal(arr[0]);
                    if (arr.Length == 2)
                    {
                        decimal maxDiscount = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.Discount >= minDiscount);
                        infolist = infolist.Where(s => s.Discount <= maxDiscount);
                    }
                    else
                    {
                        infolist = infolist.Where(s => s.Discount == minDiscount);
                    }
                }
            }
            #endregion
            #region 排序
            string[] orderarr = new string[] { "", "" };
            if (!string.IsNullOrEmpty(sortOrder))
                orderarr = sortOrder.Split('-');
            string orderFeild = "Date";
            string order = "Desc";

            orderFeild = orderarr[0];
            if (orderarr.Length == 1)
                order = "Asc";
            if (order == "Asc")
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderBy(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderBy(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderBy(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                            .ThenByDescending(p => p.TopDate)
                            .ThenByDescending(p => p.AlertDate)
                            .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            else
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderByDescending(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderByDescending(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderByDescending(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                            .ThenByDescending(p => p.TopDate)
                            .ThenByDescending(p => p.AlertDate)
                            .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            #endregion
            int pageSize = DataConstants.morePageSize;
            int pageIndex = page ?? 1;
            PagedList<PublichInformation> temp = infolist.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("_SearchList", temp);
            #endregion

            return View(temp);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="PromotionType">main:主体部分 sidle:侧着上的</param>
        /// <param name="PromotionTypeId">类别ID</param>
        /// <param name="typeId">网店：1 实体店：2</param>
        /// <param name="sortOrder"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult MoreList(string PromotionType, string PromotionTypeId, int? typeId, string sortOrder, int? page = 1)
        {
            var Category = (from q in db.SysItemDetials where q.ItemDeitalID == PromotionTypeId select q).FirstOrDefault();
            ViewData["CategoryName"] = Category != null ? Category.itemDetialName : "";
            ViewData["PromotionType"] = PromotionType;
            ViewData["PromotionTypeId"] = PromotionTypeId;
            ViewData["type"] = typeId != null ? typeId.ToString() : "";
            #region 跟据类别获得商品列表
            IQueryable<PublichInformation> infolist = db.PublichInformations.Where(q => q.Status == DataConstants.Normal);
            switch (PromotionType)
            {
                case "main":
                    infolist = from q in db.PublichInformations
                               where q.PromotionType == PromotionTypeId
                               select q;
                    break;
                case "sidle":
                    infolist = from q in db.PublichInformations
                               where q.AreaType == PromotionTypeId
                               select q;
                    break;
                default:
                    break;
            }
            if (typeId != null)
            {
                infolist = infolist.Where(q => q.InfoType == typeId);
            }
            #region 筛选信息
            double highestPrice = 0;
            if (infolist != null && infolist.Count() > 0)
                highestPrice = Convert.ToDouble(infolist.Max(s => s.PresentPrice));
            ViewData["highestPrice"] = highestPrice;

            if (Request.QueryString["p"] != null)
            {
                string pvalue = Request.QueryString["p"].ToString();
                if (pvalue != "all")
                {
                    string[] arr = pvalue.Split('-');
                    decimal minPrice = Convert.ToDecimal(arr[0]);
                    infolist = infolist.Where(s => s.PresentPrice > minPrice);
                    if (arr[1] != "")
                    {
                        decimal maxPrice = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.PresentPrice < maxPrice);
                    }
                }
            }
            if (Request.QueryString["d"] != null)
            {
                string dvalue = Request.QueryString["d"].ToString();
                if (dvalue != "all")
                {
                    string[] arr = dvalue.Split('-');
                    decimal minDiscount = Convert.ToDecimal(arr[0]);
                    if (arr.Length == 2)
                    {
                        decimal maxDiscount = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.Discount >= minDiscount);
                        infolist = infolist.Where(s => s.Discount <= maxDiscount);
                    }
                    else
                    {
                        infolist = infolist.Where(s => s.Discount == minDiscount);
                    }
                }
            }
            #endregion
            #region 排序
            string[] orderarr = new string[] { "", "" };
            if (!string.IsNullOrEmpty(sortOrder))
                orderarr = sortOrder.Split('-');
            string orderFeild = "Date";
            string order = "Desc";

            orderFeild = orderarr[0];
            if (orderarr.Length == 1)
                order = "Asc";
            if (order == "Asc")
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderBy(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderBy(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderBy(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                        .ThenByDescending(p => p.TopDate)
                        .ThenByDescending(p => p.AlertDate)
                        .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            else
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderByDescending(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderByDescending(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderByDescending(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                        .ThenByDescending(p => p.TopDate)
                        .ThenByDescending(p => p.AlertDate)
                        .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            #endregion
            int pageSize = DataConstants.morePageSize;
            int pageIndex = page ?? 1;
            PagedList<PublichInformation> temp = infolist.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("_SearchList", temp);
            #endregion

            return View(temp);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sortOrder"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult SiteList(string SiteId, string sortOrder, int? page = 1)
        {
            var Category = (from q in db.SysItemDetials where q.ItemDeitalID == SiteId select q).FirstOrDefault();
            ViewData["SiteName"] = Category != null ? Category.itemDetialName : "";
            #region 跟据类别获得商品列表
            IQueryable<PublichInformation> infolist = db.PublichInformations.Where(q => q.Status == DataConstants.Normal && q.InfoSource == SiteId);
            #region 筛选信息
            double highestPrice = 0;
            if (infolist != null && infolist.Count() > 0)
                highestPrice = Convert.ToDouble(infolist.Max(s => s.PresentPrice));
            ViewData["highestPrice"] = highestPrice;

            if (Request.QueryString["p"] != null)
            {
                string pvalue = Request.QueryString["p"].ToString();
                if (pvalue != "all")
                {
                    string[] arr = pvalue.Split('-');
                    decimal minPrice = Convert.ToDecimal(arr[0]);
                    infolist = infolist.Where(s => s.PresentPrice > minPrice);
                    if (arr[1] != "")
                    {
                        decimal maxPrice = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.PresentPrice < maxPrice);
                    }
                }
            }
            if (Request.QueryString["d"] != null)
            {
                string dvalue = Request.QueryString["d"].ToString();
                if (dvalue != "all")
                {
                    string[] arr = dvalue.Split('-');
                    decimal minDiscount = Convert.ToDecimal(arr[0]);
                    if (arr.Length == 2)
                    {
                        decimal maxDiscount = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.Discount >= minDiscount);
                        infolist = infolist.Where(s => s.Discount <= maxDiscount);
                    }
                    else
                    {
                        infolist = infolist.Where(s => s.Discount == minDiscount);
                    }
                }
            }
            #endregion
            #region 排序
            string[] orderarr = new string[] { "", "" };
            if (!string.IsNullOrEmpty(sortOrder))
                orderarr = sortOrder.Split('-');
            string orderFeild = "Date";
            string order = "Desc";

            orderFeild = orderarr[0];
            if (orderarr.Length == 1)
                order = "Asc";
            if (order == "Asc")
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderBy(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderBy(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderBy(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                        .ThenByDescending(p => p.TopDate)
                        .ThenByDescending(p => p.AlertDate)
                        .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            else
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderByDescending(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderByDescending(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderByDescending(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                        .ThenByDescending(p => p.TopDate)
                        .ThenByDescending(p => p.AlertDate)
                        .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            #endregion
            int pageSize = DataConstants.morePageSize;
            int pageIndex = page ?? 1;
            PagedList<PublichInformation> temp = infolist.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("_SearchList", temp);
            #endregion

            return View(temp);
        }

        public ActionResult ProductDetails(string id)
        {
            ViewData["ProductMenu"] = comm.getProductCategoryList();
            InformationReview commons = new InformationReview();
            commons.InformationID = id;
            ViewData["InformationReview"] = commons;
            PublichInformation pi = db.PublichInformations.Where(e => e.InformationID == id).FirstOrDefault();
            pi.VisitsNumber++;
            db.SaveChanges();
            ViewData["categoryId"] = pi.ItemDeitalID;
            ViewData["type"] = pi.InfoType;
            ViewData["LeftSaildProducts"] = comm.getProductListByCategory(pi.ItemDeitalID).Where(q => q.InfoType == pi.InfoType).ToList().Take(8);
            ViewData["TuijianProducts"] = db.PublichInformations.Where(q => q.AreaType == "9809a80e-d62d-4b79-8300-54edb5ae8724").OrderByDescending(q => q.PublishDate).Take(4).ToList<PublichInformation>();
            return View(pi);
        }

        [HttpPost]
        public JsonResult AddVisitNumber(string id)
        {
            PublichInformation pi = db.PublichInformations.Where(e => e.InformationID == id).FirstOrDefault();
            pi.VisitsNumber++;
            db.SaveChanges();
            return Json("ok");
        }

        [HttpPost]
        public ActionResult ProductDetails()
        {
            ViewData["ProductMenu"] = comm.getProductCategoryList();
            string informationID = Request.Form["InformationID"];
            if (ModelState.IsValid)
            {

                if (!string.IsNullOrEmpty(informationID))
                {
                    string reviewContent = Request.Form["reviewContent"];
                    InformationReview Entity = new InformationReview();
                    Entity.InformationID = informationID;
                    Entity.ReviewID = Guid.NewGuid().ToString();
                    Entity.ReViewContent = reviewContent;
                    Entity.CreateDate = DateTime.Now;
                    MembershipUser user = Membership.GetUser();
                    if (user == null)
                    {
                        Entity.NickName = "游客";
                    }
                    else
                    {
                        Entity.NickName = user.ProviderName;
                        Entity.UserID = user.ProviderUserKey.ToString();
                    }
                    try
                    {
                        db.InformationReviews.Add(Entity);
                        db.SaveChanges();
                    }
                    catch (DbEntityValidationException dbEx)
                    {

                    }

                }
            }
            return RedirectToAction("/ProductDetails/" + informationID);



        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="filedata"></param>
        /// <returns></returns>

        [HttpPost]
        public ActionResult UpLoad(HttpPostedFileBase filedata)
        {
            string userKey = Request.Form["userId"];
            string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            initImgPoth();
            foreach (Img img in conlist.getImgConfigList())
            {
                thumbnail_id = ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/" + ImgHelper.ImgRootUrl + img.foldname + "/"), thumbnail_id, img.width, img.height, filedata);
                Response.Write(thumbnail_id);
                Response.End();
            }
            if (PicNameDictionary.ContainsKey(userKey))
            {
                PicNameDictionary[userKey] = PicNameDictionary[userKey].ToString() + "," + thumbnail_id + ".jpg";
            }
            else
            {
                PicNameDictionary.Add(userKey, thumbnail_id + ".jpg" + ",");
            }
            return new EmptyResult();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeletePic(string id)
        {
            initImgPoth();
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            foreach (Img img in conlist.getImgConfigList())
            {
                DeletePic(img.foldname, id);
            }
            if (PicNameDictionary.ContainsKey(userKey))
            {
                string temp = PicNameDictionary[userKey].ToString();
                temp = temp.Replace(id + ",", "");

                PicNameDictionary[userKey] = PicNameDictionary[userKey].ToString().Replace(id + ",", "");
            }

            return new EmptyResult();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClearePicDictionary()
        {
            if (TempData["status"] == null || TempData["status"].ToString() != "Success")
                DeleteImgsInDic();//清除缓存中的图片
            RemovePicDic();//清除图片缓存
            return new EmptyResult();
        }

        #region 删除垃圾图片
        private void DeletePic(string folder, string picName)
        {
            initImgPoth();
            string url = Server.MapPath("~/" + ImgHelper.ImgRootUrl + folder + "/" + picName);
            if (System.IO.File.Exists(url))
            {
                System.IO.File.Delete(url);
            }
        }
        #endregion

        [Authorize]
        [HttpPost]
        public ActionResult Release(PublichInformation publichInformation)
        {
            if (publichInformation.InfoType == DataConstants.WebShop && comm.isExistThisUrl(publichInformation.ShopUrl))
            {
                ModelState.AddModelError("ShopUrl", "该网址已存在在其它信息中");
            }
            if (ModelState.IsValid)
            {
                MembershipUser user = Membership.GetUser();
                string faceimg = Request.Form["faceRadio"];
                publichInformation.InformationID = Guid.NewGuid().ToString();
                publichInformation.PublishDate = System.DateTime.Now;
                publichInformation.PublishID = user.ProviderUserKey.ToString();
                publichInformation.Status = 1;
                publichInformation.MapUrl = faceimg;
                publichInformation.PictureShow = getPicListXml();
                publichInformation.TopDate = DateTime.Now;
                publichInformation.AlertDate = DateTime.Now;
                publichInformation.PriorityLevel = 0;
                if (publichInformation.StartDate == null)
                    publichInformation.StartDate = DateTime.Now;
                if (publichInformation.EndDate == null)
                    publichInformation.EndDate = DateTime.Now.AddDays(DataConstants.ExpirationDay);
                db.PublichInformations.Add(publichInformation);
                db.SaveChanges();
                TempData["status"] = "Success";
                return RedirectToAction("ReleaseSuccess", new { id = publichInformation.InformationID });
            }
            if (publichInformation.InfoType == DataConstants.WebShop)
            {
                var sl = comm.getTypeListByIdForDropDownList(DataConstants.PromotionTypeItemID);
                var s2 = comm.getTypeListByIdForDropDownList(DataConstants.SourceTypeItemID);
                ViewBag.PromotionType = new SelectList(sl, "Id", "Name", publichInformation.PromotionType);
                ViewBag.SourceList = new SelectList(s2, "Id", "Name", publichInformation.InfoSource);
                ViewData["categoryName"] = comm.getCategroyLine(publichInformation.ItemDeitalID);
                return View("WebShop", publichInformation);
            }
            return RedirectToAction("ReleaseErroy");
        }

        public ActionResult ReleaseSuccess(string id)
        {
            PublichInformation publichInformation = (from q in db.PublichInformations
                                                     where q.InformationID == id
                                                     select q).FirstOrDefault();
            return View(publichInformation);
        }

        public ActionResult ReleaseErroy()
        {
            return View();
        }

        private string getPicListXml()
        {
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            StringBuilder sb = new StringBuilder();
            sb.Append("<imgs>");
            if (PicNameDictionary.Count > 0 && PicNameDictionary[userKey] != "")
            {
                foreach (string filename in PicNameDictionary[userKey].Split(','))
                {
                    if (filename != "")
                        sb.Append(string.Format("<filename>{0}</filename>", filename));
                }
            }
            sb.Append("</imgs>");
            return sb.ToString();
        }
        /// <summary>
        /// 删除缓存中的图片
        /// </summary>
        public void DeleteImgsInDic()
        {
            initImgPoth();
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            if (PicNameDictionary.Count > 0 && PicNameDictionary[userKey] != "")
            {
                foreach (string filename in PicNameDictionary[userKey].Split(','))
                {
                    if (filename != "")
                    {
                        foreach (Img img in conlist.getImgConfigList())
                        {
                            DeletePic(img.foldname, filename);
                        }
                    }
                }
            }
        }
        public void RemovePicDic()
        {
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            PicNameDictionary.Remove(userKey);
        }

        [HttpPost]
        public ActionResult XhUpload(HttpPostedFileBase fileData)
        {
            initImgPoth();
            XhUpLoadHelper uplaodHelper = new XhUpLoadHelper();
            Response.Charset = "UTF-8";

            // 初始化一大堆变量
            //string inputname = "filedata";//表单文件域name
            string attachdir = ImgHelper.ImgRootUrl;     // 上传文件保存路径，结尾不要带/
            int dirtype = 1;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            int maxattachsize = 2097152;     // 最大上传大小，默认是2M
            string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid";    // 上传扩展名
            int msgtype = 2;                 //返回上传参数的格式：1，只返回url，2，返回参数数组
            string immediate = Request.QueryString["immediate"];//立即上传模式，仅为演示用
            byte[] file;                     // 统一转换为byte数组处理
            string localname = "";
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            string err = "";
            string msg = "''";

            if (disposition != null)
            {
                // HTML5上传
                file = Request.BinaryRead(Request.TotalBytes);
                localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                //HttpFileCollectionBase filecollection = Request.Files;
                //HttpPostedFileBase fileData = filecollection.Get(inputname);

                // 读取原始文件名
                localname = fileData.FileName;
                // 初始化byte长度.
                file = new Byte[fileData.ContentLength];

                // 转换为byte类型
                System.IO.Stream stream = fileData.InputStream;
                stream.Read(file, 0, fileData.ContentLength);
                stream.Close();

                //filecollection = null;
            }

            if (file.Length == 0) err = "无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = uplaodHelper.GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为：" + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                attach_subdir = "ext_" + extension;
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + attach_subdir + "/";

                        // 生成随机文件名
                        Random random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            uplaodHelper.CreateFolder(Server.MapPath("~/" + attach_dir));

                            System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/" + target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }

                        // 立即模式判断

                        if (immediate == "1") target = "!" + target;
                        target = uplaodHelper.jsonString(target);
                        if (msgtype == 1) msg = "'" + target + "'";
                        else msg = "{'url':'/" + target + "','localname':'" + uplaodHelper.jsonString(localname) + "','id':'1'}";
                    }
                }
            }

            file = null;

            //Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
            return this.Content("{'err':'" + uplaodHelper.jsonString(err) + "','msg':" + msg + "}");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
